package cn.est.service.impl;

import cn.est.constants.Constants;
import cn.est.pojo.SmsLog;
import cn.est.mapper.SmsLogMapper;
import cn.est.service.SmsLogService;
import cn.est.utils.reids.RedisKeyUtils;
import cn.est.utils.reids.RedisUtils;
import cn.est.utils.sms.SendSms;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 短信记录 服务实现类
 * </p>
 *
 * @author qf
 * @since 2021-08-04
 */
@Service
public class SmsLogServiceImpl extends ServiceImpl<SmsLogMapper, SmsLog> implements SmsLogService {

    private final SendSms sendSms;
    private final RedisUtils redisUtils;

    public SmsLogServiceImpl(SendSms sendSms, RedisUtils redisUtils) {
        this.sendSms = sendSms;
        this.redisUtils = redisUtils;
    }

    @Override
    public void sendMsg(String phone, Integer codeType) {
        Integer status = Constants.Sms.STATUS_SEND_FAILED;
        // 1.验证码
        String sendCode = "0000";
        // 2.调用发送方法获得结果
        String msgResult = sendSms.send(phone, sendCode);
        if (msgResult!=null && msgResult.equals(Constants.Sms.ALI_SMS_RESSULT)){
            status = Constants.Sms.STATUS_SEND_SUCCESS;
            // 成功之后将验证码存入redis
            String key = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_SMS, codeType.toString(), phone);
            redisUtils.putValue(key, sendCode, Constants.Duration.HALF_AN_HOUR);
        }
        SmsLog smsLog = new SmsLog(phone, codeType, sendCode, msgResult, status);
        this.save(smsLog);
    }
}
